<template>
  <div class="container">

    <el-card class="table-container">
      <div style="margin: 0 10px 20px 10px">
        <el-form :inline="true" :model="searchForm" ref="searchForm" class="demo-form-inline">
          <el-form-item label="用户名" prop="userName">
            <el-col :span="22">
              <el-input v-model="searchForm.userName" :rows="5" clearable type="text" placeholder="请输入用户名" />
            </el-col>
          </el-form-item>
          <el-form-item label="手机号" prop="phone" label-width="80px">
            <el-col :span="22">
              <el-input v-model="searchForm.phone" :rows="5" clearable type="text" placeholder="请输入电子邮件" />
            </el-col>
          </el-form-item>
          <el-form-item label="部门" prop="deptName" label-width="80px">
            <el-col :span="22">
              <el-input v-model="searchForm.deptName" :rows="5" clearable type="text" placeholder="请输入电子邮件" />
            </el-col>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :loading="queryLoading" @click="handleQuery">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="resetForm">重置</el-button>
          </el-form-item>
          <!-- <el-form-item>
            <el-button type="primary" @click="handleAdd">新增用户</el-button>
          </el-form-item> -->
          <el-form-item>
            <el-button type="success" plain @click="handleExportExcel">导入用户</el-button>
          </el-form-item>
          <!-- <el-form-item>
            <el-button type="primary" plain @click="handleTemplateExcel">导出用户Excel模板</el-button>
          </el-form-item> -->
        </el-form>
      </div>
      <el-table v-loading="queryLoading" :data="tableData.list" :header-row-class-name="'table-head-th'" row-key="id"
        fit highlight-current-row>

        <el-table-column align="center" key="username" show-overflow-tooltip prop="userName" label="SmapUid" />
        <el-table-column align="center" key="realName" show-overflow-tooltip prop="realName" label="真实姓名" />
        <el-table-column align="center" key="phone" show-overflow-tooltip prop="phone" label="手机号" />
        <el-table-column align="center" key="userType" show-overflow-tooltip prop="userType" label="人员类型" />
        <el-table-column align="center" key="deptName" show-overflow-tooltip prop="deptName" label="部门" />
        <el-table-column align="center" key="gender" show-overflow-tooltip prop="gender" label="性别" />
        <el-table-column align="center" key="age" show-overflow-tooltip prop="age" label="年龄" />
        <el-table-column align="center" key="amount" show-overflow-tooltip prop="amount" label="套餐额度" />
        <el-table-column align="center" key="issubmit" show-overflow-tooltip prop="issubmit" label="是否预约" >
          <template slot-scope="scope">

            <el-tag type="danger" v-if="!scope.row.issubmit">
               未预约
              </el-tag>
              <el-tag type="success" v-else>
               已预约
              </el-tag>
          </template>

        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button-group>
              <el-button size="mini" title="权限管理" type="primary" @click="handlePerm(scope.$index, scope.row)">
                <i class="fa fa-pencil" />
              </el-button>

            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页信息 -->
      <div class="pagination-container">
        <el-pagination :current-page="pageNum" :total="tableData.total" background
          layout="total, prev, pager, next, jumper" @current-change="handlePageChange"
          @size-change="handleSizeChange" />
      </div>
    </el-card>
    <el-dialog :visible.sync="addUserDialog" width="30%" :title="dialogType == 'edit' ? '编辑用户' : '新建用户'">
      <el-form ref="registerForm" :model="registerForm" :rules="registerRules" class="register-form" label-width="100px"
        label-position="left">
        <div class="text item">
          <el-form-item prop="userName" label="SmapUid">
            <el-col :span="16">
              <el-input v-model="registerForm.userName" placeholder="请输入SmapUid 如lizhitao@sn.cmcc" name="userName"
                type="text" auto-complete="on" />
            </el-col>
          </el-form-item>
          <el-form-item prop="realName" label="真实姓名">
            <el-col :span="16">
              <el-input v-model="registerForm.realName" placeholder="请输入真实姓名" name="realName" type="text"
                auto-complete="on" />
            </el-col>
          </el-form-item>
          <!-- <el-form-item prop="email" label="邮箱">
            <el-col :span="16">
              <el-input v-model="registerForm.email" placeholder="请输入邮箱" name="email" type="text" auto-complete="on" />
            </el-col>
          </el-form-item> -->
          <el-form-item prop="roleIds" label="角色">
            <el-col :span="16">
              <el-select style="width: 100%;" v-model="registerForm.roleIds" placeholder="请选择角色">
                <el-option v-for="item in rolesOptions" :key="item.id" :label="item.description" :value="item.id" />
              </el-select>
            </el-col>
          </el-form-item>
          <!-- <el-form-item prop="deptId" label="部门">
            <el-col :span="16">
              <el-select style="width: 100%;" v-model="registerForm.deptId" placeholder="请选择" ref="selectTree">
                <el-option :key="treeForm.id" :value="treeForm.id" :label="treeForm.label" hidden />
                <el-tree :data="DepartmentList" :props="defaultProps" node-key="id" accordion highlight-current
                  @node-click="handleNodeClick" />
              </el-select>
            </el-col>
          </el-form-item> -->
          <div class="button-container" style="text-align: center">
            <el-button :loading="loading" type="primary" @click.native.prevent="handleRegister">{{
              dialogType == 'edit' ? '修改' : '注册' }}</el-button>
          </div>
        </div>
      </el-form>
    </el-dialog>
    <el-dialog :visible.sync="importingDialog" width="30%" title="用户批量导入">
      <div style="width: 100%;display: flex;justify-content: center;">
        <el-upload drag :action="action" ref="uploadFile" accept=".xlsx, .xls" :headers="headers" :limit="1"
          :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess" :on-error="handleAvatarError">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传xlsx文件</div>
        </el-upload>
      </div>

    </el-dialog>
     <!-- 详情弹窗 -->
     <el-dialog :visible.sync="PermFormVisible"  width="40%" title="权限管理">
      <el-form ref="PermForm" :model="PermForm" :rules="formRules">
        <el-form-item key="userName" label="用户名" label-width="100px">
          <el-col :span="22">
            <el-input v-model="PermForm['userName']" :rows="5" :disabled="true" auto-complete="off" />
          </el-col>
        </el-form-item>
        <el-form-item label="用户角色" prop="checkedPart" label-width="100px">
          <el-col :span="22" class="checkbox-group">
            <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate"
              @change="handleCheckAllChange">全选</el-checkbox>
            <el-checkbox-group v-model="PermForm['checkedPart']" size="mini" @change="handlecheckedPartChange">
              <el-checkbox v-for="role in rolesOptions" v-if="role['role'] !== 'superadmin'" :key="role['id']"
                :label="role['role']" name="checkedPart" class="checkboxContent" border>{{ role['description']
                }}</el-checkbox>
            </el-checkbox-group>
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="SubmitCancel">取 消</el-button>
        <el-button type="primary" @click="SubmitPerForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { Message } from 'element-ui'
import SysUserApi from '../api/sysUser'
import SysRoleApi from '@/modules/sys_role/api/sysRole'
import UserRoleRelApi from '@/modules/sys_role/api/userRoleRel'
import { validateAlphabets, validEmail, validPhone } from '@/utils/validate'
import RegisterApi from '@/modules/register/api/register'
import sha256 from 'js-sha256'
// import SysDepartmentApi from "@/modules/department/api/department";
import axios from 'axios'
import URL from '@/api/api'
import { getToken } from '@/utils/auth'
export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        true: 'success',
        false: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    const validateUserPhone = (rule, value, callback) => {
      if (!validPhone(value)) {
        callback(new Error('请输入正确的用户名'))
      } else {
        callback()
      }
    }
    const validateUserEmail = (rule, value, callback) => {
      if (!validEmail(value)) {
        callback(new Error('请输入正确的邮箱'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('输入的密码不少于6位'))
      } else {
        callback()
      }
    }
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.registerForm.password) {
        callback(new Error('两次输入密码不一样'))
      } else {
        callback()
      }
    }
    return {
      checkAll: false,
      isIndeterminate: true,
      queryLoading: false,
      /* 搜索面板数据*/
      searchConfig: [],
      /* 搜索请求数据*/
      searchForm: {},
      pageSize: 10,
      pageNum: 1,
      /* 表格面板数据*/
      tableConfig: [],
      // 表格数据
      tableData: {
        results: []
      },
      dialogForm: {},
      PermForm: {
        id: '',
        username: '',
        checkedPart: [],
        email: ""
      },
      dialogType: 'see',
      dialogFormVisible: false,
      PermFormVisible: false,
      addUserDialog: false,
      formLabelWidth: '120px',
      rolesOptions: [],
      passwordType: 'password',
      registerForm: {
        username: '',
        roleIds: [],
        realName: '',
        password: 'abcd123490',
        confirmPassword: 'abcd123490',
        email: '',
        deptId: ''
      },
      registerRules: {
        userName: [{ required: true, trigger: 'blur', message: '请输入' }],
        realName: [{ required: true, trigger: 'blur', message: '请输入真实姓名' }],
        email: [{ required: true, trigger: 'blur', validator: validateUserEmail }],
        roleIds: [{ required: true, trigger: 'change', message: '请选择角色' }],
        deptId: [{ required: true, trigger: 'change', message: '请选择部门' }],
      },
      // 角色列表
      rolesList: [],
      loading: false,
      showDialog: false,
      redirect: undefined,
      capsTooltip: false,
      formRules: {
        checkedPart: [{ type: 'array', required: true, message: '至少选择一个部分', trigger: 'change' }],
        email: [{ required: true, trigger: 'blur', validator: validateUserEmail }]
      },
      DepartmentList: [],
      defaultProps: {
        children: 'children',
        label: 'departmentName'
      },
      treeForm: {
        id: '',
        value: ''
      },
      Departments: [],
      importingDialog: false,
      action: URL + "/api/users/import",
      headers: {
        Authorization: getToken(),
      },
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    handlePerm(index, row) {

      this.PermForm.id = row.id
      this.PermForm.userName = row.userName
      this.PermForm.email = row.email
      this.PermForm.deptId = row.deptId
      this.getThisUserRole(row.id)
      this.PermFormVisible = true
    },


    resetForm() {
      this.$refs.searchForm.resetFields()
      this.searchForm={
        userName:"",
        phone:"",
        deptName:""
      },
      this.init()
    },
    // 页面初始化
    init() {
      this.getAllRole()

      this.query()
    },
    checkCapslock({ shiftKey, key } = {}) {
      if (key && key.length === 1) {
        if (shiftKey && (key >= 'a' && key <= 'z') || !shiftKey && (key >= 'A' && key <= 'Z')) {
          this.capsTooltip = true
        } else {
          this.capsTooltip = false
        }
      }
      if (key === 'CapsLock' && this.capsTooltip === true) {
        this.capsTooltip = false
      }
    },
    handleQuery() {
      this.query()
    },
    handleCheckAllChange(val) {
      this.PermForm.checkedPart = val ? this.rolesList : []
      this.isIndeterminate = false
    },
    handlecheckedPartChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.rolesList.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.rolesList.length
    },
    // getDepartment() {
    //   return new Promise((resolve, reject) => {
    //     this.queryLoading = true;
    //     const param = Object.assign({}, this.searchForm);
    //     SysDepartmentApi.queryTree(param)
    //       .then((response) => {
    //         const data = response.data;
    //         if (data.code === 200) {
    //           const data = response.data.data;
    //           this.DepartmentList = data;
    //           this.Departments = this.traverseTree(data)

    //         } else {
    //           Message.error(data.message);
    //           reject();
    //         }
    //       })
    //       .catch((error) => {
    //         if (error.message !== "") {
    //           //Message.error(error.message)
    //         }
    //         reject(error);
    //       });
    //   });
    // },
    getThisUserRole(id) {
      return new Promise((resolve, reject) => {
        SysRoleApi
          .queryUserRole(id)
          .then(response => {
            const data = response.data
            if (data.code === 200) {
              const data = response.data.data
              this.PermForm.checkedPart = data
            } else {
              Message.error(data.message)
              reject()
            }
          })
          .catch(error => {
            // Message.error(error.message || error || "未知错误")

            reject(error)
          })
      })
    },
    getAllRole() {
      return new Promise((resolve, reject) => {
        SysRoleApi
          .query()
          .then(response => {
            const data = response.data
            if (data.code === 200) {
              const data = response.data.data
              this.rolesOptions = data.list
              console.log(this.rolesOptions, 111111111)
              for (var role in data.list) {
                this.rolesList.push(data.list[role].role)
              }
            } else {
              Message.error(data.message)
              reject()
            }
          })
          .catch(error => {
            // Message.error(error.message || error || "未知错误")
            reject(error)
          })
      })
    },
    query() {
      this.queryLoading = true
      return new Promise((resolve, reject) => {
        const param = Object.assign({}, this.searchForm)
        SysUserApi
          .queryByCond(param, this.pageSize, this.pageNum)
          .then(response => {
            const data = response.data
            this.queryLoading = false
            if (data.code === 200) {
              const data = response.data.data
              this.tableData = data
            } else {
              Message.error(data.message)
              reject()
            }
          })
          .catch(error => {
            this.queryLoading = false
            reject(error)
          })
      })
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
    },
    handleRegister() {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          this.loading = true
          const params = Object.assign({}, this.registerForm)
          params.password = sha256(this.registerForm.password)
          return new Promise((resolve, reject) => {
            if (this.dialogType == 'edit') {
              SysUserApi.update(params).then(response => {
                const data = response.data
                this.loading = false
                if (data.code === 200) {
                  Message.success('修改成功..')
                  this.addUserDialog = false
                  this.query()
                  this.$refs.registerForm.resetFields()
                } else {
                  Message.error(data.message)
                  return
                }
                resolve(data)
              })
                .catch(error => {
                  this.loading = false
                  Message.error(error.message || error || "未知错误")
                  reject(error)
                })
            } else {
              RegisterApi
                .register({ ...params, password: undefined, confirmPassword: undefined })
                .then(response => {
                  const data = response.data
                  this.loading = false
                  if (data.code === 200) {
                    Message.success('注册成功..')
                    this.addUserDialog = false
                    this.query()
                    this.$refs.registerForm.resetFields()
                  } else {
                    Message.error(data.message)
                    return
                  }
                  resolve(data)
                })
                .catch(error => {
                  this.loading = false
                  Message.error(error.message || error || "未知错误")
                  reject(error)
                })
            }

          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleAdd() {
      this.dialogType = 'add'
      this.addUserDialog = true
      this.$nextTick(() => {
        this.$refs.registerForm.resetFields()
      })
    },
    handleEdit(index, row) {
      this.dialogType = 'edit'
      this.addUserDialog = true
      this.$nextTick(() => {
        this.registerForm = row
        this.registerForm.roleIds = Number(row.roleIds)
        this.treeForm = {
          id: row.deptId,
          value: row.yytname,
          label: row.yytname
        }
      })


    },
    SubmitCancel() {
      this.dialogFormVisible = false
      this.PermFormVisible = false
      this.query()
    },
    SubmitPerForm(row) {
      this.loading = true
      this.$refs['PermForm'].validate(valid => {
        if (valid) {
          const params = Object.assign({}, this.PermForm)
          return new Promise((resolve, reject) => {
            UserRoleRelApi
              .updateUserRoleRel(params)
              .then(response => {
                this.loading = false
                const data = response.data
                if (data.code === 200) {
                  this.$message({
                    message: '修改成功',
                    type: 'success'
                  })
                  this.PermFormVisible = false
                  this.loading = false
                  this.query()
                } else {
                  Message.error(data.message)
                  reject()
                }
              })
              .catch(error => {
                this.loading = false
                // Message.error(error.message || error || "未知错误")
                reject(error)
              })
          })
        } else {
          this.loading = false
          return false
        }
      })
    },
    SubmitCancel() {
      this.dialogFormVisible = false
      this.PermFormVisible = false
      this.query()
    },
    // 处理翻页事件
    handlePageChange(currentPage) {
      this.pageNum = currentPage
      this.query()
    },
    // 处理页面总条数事件
    handleSizeChange(val) {
      // console.log(`每页  条`);
      this.pageSize = val
      this.query()
    },
    handleNodeClick(data) {
      this.treeForm = {
        id: data.id,
        value: data.departmentName,
        label: data.departmentName
      }
      this.registerForm.deptId = data.id
      // 使 input 失去焦点，并隐藏下拉框
      this.$refs.selectTree.blur()
    },
    handleDel(row) {
      this.$confirm('确定删除吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const param = Object.assign({}, row)
          SysUserApi
            .delete(param)
            .then(response => {
              const data = response.data
              if (data.code === 200) {
                this.$message({
                  message: '删除成功',
                  type: 'success'
                })
                this.handleQuery()
              } else {
                Message.error(data.message)
              }
            })
            .catch(error => {
              // console.log(error)
              // Message.error(error.message || error || "未知错误")
            })
        })
        .catch(() => {
        })
    },

    handleTemplateExcel() {
      SysUserApi.exportData().then(res => {

        const url = window.URL.createObjectURL(new Blob([res.data]))
        const link = document.createElement("a")
        link.href = url
        link.setAttribute("download", '模板文件.xlsx')//导出的格式一定要和接口返回的文件一致
        document.body.appendChild(link)
        link.click()
        window.URL.revokeObjectURL(url)
        document.body.removeChild(link)
      })
      // const fileUrl = URL + minioUrl+'/api/users/template';
      // const link = document.createElement('a');
      // link.href = fileUrl;
      // link.download = 'template.xls';
      // document.body.appendChild(link);
      // link.click();
      // document.body.removeChild(link);
    },
    handleExportExcel() {
      this.importingDialog = true
      this.$refs.uploadFile.clearFiles()
    },
    traverseTree(nodes, result = []) {
      nodes.forEach(node => {
        result.push({ id: node.id, name: node.departmentName });
        if (node.children) {
          this.traverseTree(node.children, result); // 递归调用处理子节点
        }
      });
      return result;
    },

    beforeAvatarUpload(file) {
      const extension = file.name.split(".")[1] === "xls";
      const extension2 = file.name.split(".")[1] === "xlsx";
      if (!extension && !extension2) {
        this.$message.error("上传文件只能是 xls、xlsx 格式!");
        return false;
      }
    },
    handleAvatarSuccess(resp) {
      if (resp.code == 200) {
        Message.success("导入成功")
        this.query()
      } else {
        Message.error("导入失败")
      }
      this.importingDialog = false
    },
    handleAvatarError() {
      Message.error("文件上传失败")

    }
  },

}
</script>
<style>
.container {
  margin: 10px;
}

.table-container {
  margin-top: 0px;
}

.pagination-container {
  margin-top: 30px;
  text-align: right;
}

.show-pwd {
  position: absolute;
  right: 10px;
  top: 7px;
  font-size: 16px;
  color: #889aa4;
  cursor: pointer;
  user-select: none;
}
</style>
